//
//  GameMovingObject.m
//  HelloWorldGame
//
//  Created by huji on 13-2-3.
//
//

#import "GameMovingObject.h"
#import "cocos2d.h"

@interface GameMovingObject ()
@property (nonatomic,retain) CCSprite *_sprite;
@property (nonatomic,retain) NSMutableDictionary *userinfo;
@end

@implementation GameMovingObject

-(void)dealloc{
    self._sprite=nil;
    [super dealloc];
}

+(id)objectWithImage:(NSString*)imageName row:(int)row column:(int)column size:(CGSize)size{
    return [[[self class] alloc] initWithImage:imageName row:row column:column size:size];
}

-(id)init{
    self = [super init];
    if (self) {
        self.speed = 30;
        self.userinfo = [NSMutableDictionary dictionaryWithCapacity:10];
        self.life=10;
    }
    return self;
}

-initWithImage:(NSString*)imageName row:(int)row column:(int)column size:(CGSize)size{
    self = [self init];
    if (self) {
        
        CCTexture2D *texture = [[CCTextureCache sharedTextureCache] addImage:imageName];
        for (int i =0; i<row; i++) {
            NSMutableArray *frames_ = [NSMutableArray arrayWithCapacity:column];
            for (int j=0; j<column; j++) {
                CCSpriteFrame *frame_ = [CCSpriteFrame frameWithTexture:texture rect:CGRectMake(j*size.width, i*size.height, size.width, size.height) ];
                [frames_ addObject:frame_];
                if (i==0&&j==0) {
                    self._sprite = [CCSprite spriteWithSpriteFrame:frame_];
                }
            }
            CCAnimation *animation_ = [CCAnimation animationWithSpriteFrames:frames_ delay:35/self.speed];
            CCAnimate *animate_ = [CCAnimate actionWithAnimation:animation_];
            animate_.duration=0.3f;
            CCRepeatForever *action_ = [CCRepeatForever actionWithAction:animate_];
            [self.userinfo setObject:action_ forKey:[NSNumber numberWithInt:i]];
        }
    }
    return self;
}

-(void)sendAction:(int)actiontype object:(id)obj{
    [self._sprite stopAllActions];
    
    if (actiontype==MovingObject_Action_Move) {
        NSValue *value = obj;
        CGPoint to = [value CGPointValue];
        float dx = to.x-self._sprite.position.x;
        float dy = to.y-self._sprite.position.y;
        if (fabsf(dx)>fabsf(dy)) {
            if (dx>0) {
                [self._sprite runAction:[self.userinfo objectForKey:[NSNumber numberWithInt:2]]];
            }else{
                [self._sprite runAction:[self.userinfo objectForKey:[NSNumber numberWithInt:1]]];
            }
        }else{
            if (dy>0) {
                [self._sprite runAction:[self.userinfo objectForKey:[NSNumber numberWithInt:3]]];
            }else{
                [self._sprite runAction:[self.userinfo objectForKey:[NSNumber numberWithInt:0]]];
            }
        }
        [self._sprite runAction:[CCMoveTo actionWithDuration:ccpDistance(to, self._sprite.position)/self.speed position:to]];
    }
}

-(CCSprite*)sprite{
   return self._sprite;
}

@end
